package com.moussa.mike;

import java.util.List;

public class YouTubeSearchAPI {
	private static String devKey = "ENTER YOUR DEV KEY HERE";
	private static String searchUrlTemplate = "http://gdata.youtube.com/feeds/api/videos?q=%s&v=2&format=1,6&max-results=%d&fields=openSearch:totalResults,entry(title,content,author(name),media:group(media:category(@label,text()),yt:duration),gd:rating(@average),yt:statistics)&key=%s";

	public static List<YouTubeVideo> doSearch(String query, int maxResultCount)
	{
		String searchUrl = String.format(searchUrlTemplate,query,maxResultCount,devKey);
		XMLHandler xml = new XMLHandler(searchUrl);
		List<YouTubeVideo> vids = xml.ParseXML();
		if (vids != null)
		{
			for (YouTubeVideo vid : vids)
			{
				int noCaptionCount = doCountQuery(searchUrl,vid.getAuthor(),false);
				int captionCount = doCountQuery(searchUrl,vid.getAuthor(),true);
				vid.setUserCounts(captionCount, captionCount + noCaptionCount);
			}
		}
		return vids;
	}

	private static int doCountQuery(String searchUrl, String author, boolean doCaption)
	{
		XMLHandler xml = new XMLHandler(searchUrl);
		return xml.ParseXMLForCount(author, doCaption);
	}

}
